//
//  RHNetworkConfigResultVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/1.
//

#import "RHNetworkConfigResultVC.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "DevSocketManage.h"
#import <NetworkExtension/NetworkExtension.h>

typedef NS_ENUM(NSInteger,DeviceState) {
    DeviceStateConnecting = 0,
    DeviceStateConnectFail,
    DeviceStateConnectSuccess
};

@interface RHNetworkConfigResultVC ()<DevSocketProtocal>
@property(nonatomic,strong)YYAnimatedImageView *animateImg;

@property(nonatomic,strong)UIImageView *statusImg;

@property(nonatomic,strong)UIImageView *finishImg;

@property(nonatomic,strong)QMUILabel *progressLab;

@property(nonatomic,strong)QMUILabel *statusLab;

@property(nonatomic,strong)QMUILabel *tipsLab;

@property(nonatomic,strong)QMUIButton *sureBtn;

@property(nonatomic,assign)DeviceState connectState;
//进度计数
@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,assign)NSInteger count;
@end

@implementation RHNetworkConfigResultVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"配网".rh_localized;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
    [self updateUIWithState:DeviceStateConnecting];
    [DevSocketManage shareSocketManage].delegate = self;
}

-(void)DevSocket:(GCDAsyncSocket *)sock didReceiveData:(NSString *)data withTag:(long)tag
{
    
    if([data containsString:@"-WIFICONFIG"]){
        //收到设备回复的指令会断开设备的热点连接,重新连接回之前的wifi,然后定时轮询设备的在线状态,以确定设备是否配网成功
        NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:self.lastSSID passphrase:self.ssidPWD isWEP:NO];
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
            [self.timer invalidate];
            self.timer = nil;
            self.count = 0;
            self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timePlus) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              NSInteger time =  [[NSDate date]timeIntervalSince1970]*1000;
                NSDictionary *para = @{@"account":[PrivateMange share].currentUser.email,
                                       @"deviceId":self.deviceId,
                                       @"timestamp":@(time)
                };
                //发送配网记录
                [BaseModel startWithCompletionAPIKey:H_netRecord argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                    
                } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                    
                }];
            });
        }];
    }
    
}

-(void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectSuccessful) name:NetwordConfigSuccessNotification object:nil];
    
    kWeakSelf;
    QMUILabel *progressLab = [[QMUILabel alloc]init];
    progressLab.textAlignment = NSTextAlignmentCenter;
    progressLab.text = @"0%";
    progressLab.textColor = kCOLOR_HEX(@"3F4443");
    progressLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:progressLab];
    self.progressLab = progressLab;
    

    [progressLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.view);
            make.centerY.equalTo(weakSelf.view);
    }];
    
    self.animateImg = [[YYAnimatedImageView alloc]initWithImage:[YYImage imageNamed:@"network_config.gif"]];
    self.animateImg.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.animateImg];
    [self.animateImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(weakSelf.view).multipliedBy(0.5);
        make.bottom.equalTo(progressLab.mas_top).offset(kScaleW(30));
            make.centerX.equalTo(weakSelf.view);
            make.top.equalTo(weakSelf.view).offset(kScaleW(30));
    }];
    
    self.statusImg = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"network_finish"]];
    self.statusImg .contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.statusImg ];
    
    [self.statusImg  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.animateImg);
    }];
    
    UIImageView *finishImg = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"network_success"]];
    finishImg.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:finishImg];
    self.finishImg = finishImg;
    [finishImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(50));
        make.centerX.centerY.equalTo(weakSelf.progressLab);
    }];
    
    QMUILabel *statusLab = [[QMUILabel alloc]init];
    statusLab.textAlignment = NSTextAlignmentCenter;
    statusLab.text = @"设备正在连接...".rh_localized;
    statusLab.textColor = kCOLOR_HEX(@"3F4443");
    statusLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:statusLab];
    self.statusLab = statusLab;
    [statusLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(progressLab);
            make.top.equalTo(progressLab.mas_bottom).offset(kScaleW(40));
    }];
    
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.text = @"连接过程中请避免设备断电".rh_localized;
    tipsLab.numberOfLines = 0;
    tipsLab.textColor = kCOLOR_HEX(@"3F4443");
    tipsLab.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:tipsLab];
    self.tipsLab = tipsLab;
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(statusLab);
            make.top.equalTo(statusLab.mas_bottom).offset(kScaleW(10));
    }];
    
    

    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.backgroundColor = CMainColorGreen;
    sureBtn.enabled = NO;
    sureBtn.layer.cornerRadius = 8;
    sureBtn.layer.masksToBounds = YES;
    [sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    self.sureBtn = sureBtn;
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-20-kSafe_bottom);
            make.height.offset(kScaleW(45));
    }];
}

-(void)updateUIWithState:(DeviceState)state
{
    self.connectState = state;
    switch (state) {
        case DeviceStateConnecting:
            {
                [self connecting];
            }
            break;
        case DeviceStateConnectFail:
            {
                [self connectFail];
            }
            break;
        case DeviceStateConnectSuccess:
            {
                [self connectSuccessful];
            }
            break;
        default:
            break;
    }
}

-(void)connecting
{
    self.animateImg.hidden = NO;
    [self.animateImg startAnimating];
    self.statusImg.hidden = YES;
    self.finishImg.hidden = YES;
    self.progressLab.hidden = NO;
    self.statusLab.hidden = NO;
    self.statusLab.text = @"设备正在连接...".rh_localized;
    self.tipsLab.hidden = NO;
    self.tipsLab.text = @"连接过程中请避免设备断电".rh_localized;
    
}
-(void)connectFail
{
    [self.animateImg stopAnimating];
    self.animateImg.hidden = YES;
    self.statusImg.hidden = NO;
    self.finishImg.hidden = NO;
    self.finishImg.image = [UIImage imageNamed:@"network_fail"];
    self.progressLab.hidden = YES;
    self.statusLab.hidden = NO;
    self.statusLab.text = @"设备连接失败".rh_localized;
    self.tipsLab.hidden = NO;
    self.tipsLab.text = @"请点击下方重试按钮，重新连接".rh_localized;
    [self.sureBtn setTitle:@"retry" forState:UIControlStateNormal];
    self.sureBtn.enabled = YES;
}
-(void)connectSuccessful
{
    [self.animateImg stopAnimating];
    self.animateImg.hidden = YES;
    self.statusImg.hidden = NO;
    self.finishImg.hidden = NO;
    self.finishImg.image = [UIImage imageNamed:@"network_success"];
    self.progressLab.hidden = YES;
    self.statusLab.hidden = NO;
    self.statusLab.text = @"设备连接成功".rh_localized;
    self.tipsLab.hidden = YES;
    [self.sureBtn setTitle:@"完成".rh_localized forState:UIControlStateNormal];
    self.sureBtn.enabled = YES;
    
    [[DevSocketManage shareSocketManage]disconnect];
}

-(void)timePlus
{
    self.count ++;
    NSString *content = [NSString stringWithFormat:@"%zd%%",self.count];
    self.progressLab.text = content;
    
    if(self.count == 100){
        [self.timer invalidate];
        self.timer = nil;
        [self updateUIWithState:DeviceStateConnectFail];
    }
    
    if(self.count%5==0){
        [BaseModel startGetWithCompletionAPIKey:H_deviceBindStatus argument:@{@"deviceId":self.deviceId,@"password":self.password} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
            if(resultModel.code == 200){
                if([request.responseJSONObject[@"data"][@"status"] isEqualToString:@"0"]){
                    [self updateUIWithState:DeviceStateConnectSuccess];
                }
            }
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
            
        }];
    }
    
}


-(void)sureAction:(UIButton*)btn
{
    switch (self.connectState) {
        case DeviceStateConnectFail:
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
            break;
        case DeviceStateConnectSuccess:
            {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            break;
        default:
            break;
    }
    
    
}
@end
